package com.lagou.util;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.util.UUID;

@Controller
public class FileAction {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static String upload(String oldFileName){

        try{

            //通过字符串截取的方式，从文件原始名中获取文件的后缀
            String hou = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);

            //2 把文件从web服务器上传到FastDFS
            ClientGlobal.initByProperties("fastdfs/fastdfs-client.properties");
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);

            NameValuePair[] list = new NameValuePair[1];
            list[0] = new NameValuePair("fileName",oldFileName);
            String fileId = client.upload_file1(oldFileName, hou, list);
            trackerServer.close();

            return fileId;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

//    public static String upload(MultipartFile file){
//
//        try{
//            //从文件对象中获取文件的原始名称
//            String oldFileName = file.getOriginalFilename();
//
//            //1 把文件保存到web服务器
//            //通过字符串截取的方式，从文件原始名中获取文件的后缀
//            String hou = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
//            //为了避免文件因为同名而覆盖，生成全新的文件名
//            String newFileName = UUID.randomUUID().toString() + "." + hou;
//
//            //创建web服务器保存文件的目录
//            File toSaveFile = new File("F:\\Java_Learning\\拉勾java班\\代码\\练习\\stage7\\module2\\upload", newFileName);
//            //将路径转换成文件
//            file.transferTo(toSaveFile);
//            //获取服务器的绝对路径
//            String newFilePath = toSaveFile.getAbsolutePath();
//
//            //2 把文件从web服务器上传到FastDFS
//            ClientGlobal.initByProperties("fastdfs/fastdfs-client.properties");
//            TrackerClient trackerClient = new TrackerClient();
//            TrackerServer trackerServer = trackerClient.getConnection();
//            StorageServer storageServer = null;
//            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
//
//            NameValuePair[] list = new NameValuePair[1];
//            list[0] = new NameValuePair("fileName",oldFileName);
//            String fileId = client.upload_file1(newFilePath, hou, list);
//            trackerServer.close();
//
//            return fileId;
//        }catch (Exception e){
//            e.printStackTrace();
//            return null;
//        }
//    }
}
